package com.vf.admin.client.controller.pay.alipay;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.controller.pay.nopay.service.AppNoPayService;
import com.vf.admin.client.controller.pay.params.FeiParam1;
import com.vf.admin.client.controller.pay.params.FeiParam2;
import com.vf.admin.client.controller.pay.params.FeiParam3;
import com.vf.admin.client.controller.pay.params.FeiParam4;
import com.vf.admin.client.controller.pay.sandpay.SandpayService;
import com.vf.admin.client.controller.pay.sandpay.alipay.SandAliPayService;
import com.vf.admin.client.dao.VipOrderDao;
import com.vf.admin.client.enums.PayTypeEnum;
import com.vf.admin.client.result.PayInfoResult;
import com.vf.admin.client.service.*;
import com.vf.admin.common.entity.Result;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.miaodong.service.AfterAppTicketPackageService;
import com.vf.admin.miaodong.service.AfterUserService;
import com.vf.admin.utils.Md5Util1;
import com.vf.admin.utils.UaUtil;
import com.vf.admin.utils.pay.ApiAliPay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import static com.vf.admin.common.Constants.*;

/**
 * <p>Title : 支付宝支付</p>
 * <p>Description : 整合我的钱包 会员中心</p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows10</p>
 *
 * @Author : NemoMeng
 * @Date 2023/6/25 11:23
 */
@Controller
@CrossOrigin
@RequestMapping(value = "/api/aliPayVersion3")
public class ApiAliPayVersion3Controller extends ClientBaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    //支付宝充值配置业务
    @Autowired
    private AlipayConfigsService alipayConfigsService;

    //appSetup设置
    @Autowired
    private AppSetupService appSetupService;
    //用户信息
    @Autowired
    private AppUserService appUserService;
    @Autowired
    AfterUserService afterUserService;
    //充值金额信息
    @Autowired
    private AppCzMoneyService appCzMoneyService;
    //钱包订单
    @Autowired
    private AppOrderService appOrderService;
    @Autowired
    private AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    private AppMingxiChongzhiService appMingxiChongzhiService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    private AppPrivilegeService appPrivilegeService;
    @Autowired
    private AppInvitationRecordService appInvitationRecordService;
    //会员充值金额信息
    @Autowired
    private VipPackageService vipPackageService;
    //vip订单
    @Autowired
    private VipOrderService vipOrderService;
    @Autowired
    private VipOrderDao vipOrderDao;
    @Autowired
    private SandAliPayService sandAliPayService;
    @Autowired
    private SandpayService sandpayService;
    @Autowired
    private PhpUserService phpUserService;
    @Resource
    private AfterAppTicketPackageService afterAppTicketPackageService;
    @Resource
    private AppNoPayService appNoPayService;


    /**
     * 商城支付
     */
    @RequestMapping(value = "/shopH5")
    @ResponseBody
    public Result shopH5(String name, BigDecimal price) {
        PayInfoResult payInfoResult = alipayConfigsService.shopH5(name, price);
        return this.sucessJSON(payInfoResult);
    }


    /**
     * h5 下单接口
     *
     * @param type      1钻石  2会员
     * @param projectId 根据type选择 项目id
     * @return
     */
//    @RequestMapping(value = "/transactionsH5", method = RequestMethod.POST)
//    @ResponseBody
//    public Result transactionsH5(Integer type, Integer projectId, String mobileSpec,String channel) {
//
//        if (ObjectUtil.isEmpty(mobileSpec)){
//            String os = UaUtil.getOs(request);
//            if (ObjectUtil.isNotEmpty(os)){
//                mobileSpec = os;
//            }
//
//        }
//
//        if (type == 1) {
//            try {
//                //提示
//                AppSetup setup = appSetupService.get();
//                if (setup.getOpenRecharge() == 0) {
//                    return this.errorJSON(setup.getRechargeTip());
//                }
//                //获取用户信息
//                AppUser user = appUserService.get(getUserId());
//                AppCzMoney appCzMoney = appCzMoneyService.get(projectId);
//                PayInfoResult payInfoResult = alipayConfigsService.aliPayDiamondTransactionsH5(user, appCzMoney, mobileSpec);
//                if (ObjectUtil.isEmpty(payInfoResult)) {
//                    return this.errorJSON("充值失败，请您重新充值!");
//                }
//                return this.sucessJSON(payInfoResult);
//            } catch (Exception e) {
//                logger.error("支付宝充值异常:", e);
//                return this.errorJSON("服务器繁忙，请您稍后重试!");
//            }
//        }
//        if (type == 2) {
//            try {
//                //提示
//                AppSetup setup = appSetupService.get();
//                if (setup.getOpenBuyVip() == 0) {
//                    return this.errorJSON(setup.getBuyVipTip());
//                }
//                //获取用户信息
//                AppUser user = appUserService.get(getUserId());
//                VipPackage vipPackage = vipPackageService.info(projectId);
//                PayInfoResult payInfoResult = alipayConfigsService.aliPayOpenVipTransactionsH5(user, vipPackage, mobileSpec);
//                if (ObjectUtil.isEmpty(payInfoResult)) {
//                    return this.errorJSON("充值失败，请您重新充值!");
//                }
//                return this.sucessJSON(payInfoResult);
//            } catch (Exception e) {
//                logger.error("支付宝充值异常:", e);
//                return this.errorJSON("服务器繁忙，请您稍后重试!");
//            }
//        }
//
//        if (type == 3) {
//            try {
//
//                //获取用户信息
//                AppUser user = appUserService.get(getUserId());
//                VipPackage vipPackage = new VipPackage();
//                vipPackage.setId(1000);
//                vipPackage.setPrice(new BigDecimal("28.00"));
//
//
//                PayInfoResult payInfoResult = alipayConfigsService.aliPayOpenVipTransactionsH5(user, vipPackage, mobileSpec);
//                if (ObjectUtil.isEmpty(payInfoResult)) {
//                    return this.errorJSON("充值失败，请您重新充值!");
//                }
//                return this.sucessJSON(payInfoResult);
//            } catch (Exception e) {
//                logger.error("支付宝充值异常:", e);
//                return this.errorJSON("服务器繁忙，请您稍后重试!");
//            }
//        }
//
//
//        return this.errorJSON("请求参数不正确!");
//    }
    //type 4 php门票  5 php会员   userId php传入用户id  projectId 12374  price 价格
    @RequestMapping(value = "/transactionsH5")
    @ResponseBody
    public Result transactionsH5(Integer type, Integer projectId, String mobileSpec, Integer userId, BigDecimal price) throws IOException {
        //设置设备
        if (ObjectUtil.isEmpty(mobileSpec)) {
            String os = UaUtil.getOs(request);
            if (ObjectUtil.isNotEmpty(os)) {
                mobileSpec = os;
            }
        }

        //获取用户信息
        AppUser user = appUserService.get(getUserId());

        PaySelect paySelect = sandpayService.getPaySelect();
        PayInfoResult payInfoResult = null;

        switch (type){
            case 1://充值
                AppCzMoney appCzMoney = appCzMoneyService.get(projectId);
                payInfoResult = alipayConfigsService.aliPayDiamondTransactionsH5(user, appCzMoney, mobileSpec);
                break;
            case 2://vip
            case 3://门票
                //获取价格对象
                VipPackage vipPackage = new VipPackage();
                if(2==type){
                    vipPackage = vipPackageService.info(projectId);
                }else{
                    vipPackage.setId(1000);
                    AppTicketPackage appTicketPackage = afterAppTicketPackageService.getList().get(0);
                    BigDecimal money = appTicketPackage.getMoney();
                    vipPackage.setPrice(money);
                }

                //不同支付类型
                if(ObjectUtil.equal(3, paySelect.getType())){
                    //永安
                    payInfoResult = alipayConfigsService.aliPayOpenVipTransactionsH511(user, vipPackage, mobileSpec, PayTypeEnum.ALIPAY_YA, paySelect);
                }else if(ObjectUtil.equal(4, paySelect.getType())){
                    //汇付天下
                    payInfoResult = alipayConfigsService.aliPayOpenVipTransactionsH522(user, vipPackage, mobileSpec, paySelect);
                }else if(ObjectUtil.equal(5, paySelect.getType())){
                    //行者直播
                    payInfoResult = alipayConfigsService.aliPayOpenVipTransactionsH533(user, vipPackage, mobileSpec, paySelect);
                }else if(ObjectUtil.equal(6, paySelect.getType())){
                    //奈斯
                    payInfoResult = alipayConfigsService.aliPayOpenVipTransactionsH544(user, vipPackage, mobileSpec, paySelect);
                }else{
                    //原生
                    payInfoResult = alipayConfigsService.aliPayOpenVipTransactionsH5(user, vipPackage, mobileSpec);
                }
                break;
        }

        if (ObjectUtil.isEmpty(payInfoResult)) {
            return this.errorJSON("充值失败，请您重新充值!");
        }else if (ObjectUtil.isEmpty(payInfoResult.getPayUrl())){
            return this.errorJSON(payInfoResult.getMessage());
        }
        return this.sucessJSON(payInfoResult);
    }


    /**
     * 我的钱包回调接口
     */
    @RequestMapping(value = "/diamond/AiliNotifyUrl/{appIdStr}", method = RequestMethod.POST)
    @ResponseBody
    public String diamondAiliNotifyUrl(HttpServletRequest request, @PathVariable("appIdStr") String appIdStr) throws UnsupportedEncodingException {
        //获取对应详细信息
        AlipayConfigs appIdInfo = alipayConfigsService.getAppIdInfo(appIdStr);
        //通过appId获取对应账号信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, appIdInfo.getAlipayPublicKey(), AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.info("验证公钥时出现异常");
        } // 调用SDK验证签名
        logger.info("验证签名结果" + signVerified);
        //对应数据库操作
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            logger.info("-----------商户订单号" + out_trade_no);
            logger.info("-----------支付宝交易号" + trade_no);
            logger.info("-----------交易状态" + trade_status);
            //订单支付成功
            if ("TRADE_SUCCESS".equals(trade_status)) {
                //根据订单号、支付状态、支付方式获取预订单
                AppOrder topup = appOrderService.getByOrdernum(out_trade_no, dingdan_zhiFuLeiXing_zfb, dingdan_status_dfk);
                if (!StringUtils.isEmpty(topup)) {
                    AppUser user = appUserService.get(topup.getUserid());
                    //存在则更改预订单支付状态
                    appOrderService.updateStastusYzf(out_trade_no, dingdan_zhiFuLeiXing_zfb);
                    BigDecimal getDiamond = topup.getNum();
                    //添加用户钻石金额
                    appUserService.updateZuanShi(user.getId(), getDiamond);
                    //增加用户累积充值金额
                    appUserService.updateLeijiChongzhi(user.getId(), topup.getMoney());
                    //添加钻石明细
                    appMingXiZuanShiService.addMingxi(user.getId(), getDiamond, 1, "钻石充值");
                    //添加充值明细
                    appMingxiChongzhiService.addMingxi(user.getId(), getDiamond, 1, topup.getMoney(), out_trade_no, topup.getMobileSpec());
                    //完成充值任务
                    appDailyTasController.getAwardOnce(topup.getUserid(), ClientConstants.TaskOnce.RECHARGE_FIRST);
                    //如果有上级发放用户充值提成
                    addAward(topup);
                    //升级贵族
                    appPrivilegeService.isUpLevel(user);
                    logger.info("支付宝回调成功，充值入账成功");
                }
            }
        }
        return "success";
    }

    /**
     * 邀请用户充值增加父级提成
     */
    public void addAward(AppOrder order) {
        AppInvitationRecord record = appInvitationRecordService.getShangji(order.getUserid());
        if (record != null) {
            AppSetup appSetup = appSetupService.get();
            BigDecimal divide = order.getNum().multiply(appSetup.getRechargeInvite()).setScale(2, BigDecimal.ROUND_HALF_UP);
            appUserService.addDiamonds(record.getPuserid(), divide, "邀请用户充值提成");
        }
    }

    /**
     * 会员充值回调
     *
     * @param request
     * @param appIdStr 对应appId
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/vip/AiliNotifyUrl/{appIdStr}", method = RequestMethod.POST)
    @ResponseBody
    public String vipAiliNotifyUrl(HttpServletRequest request, @PathVariable("appIdStr") String appIdStr) throws UnsupportedEncodingException {
        //获取对应详细信息
        AlipayConfigs appIdInfo = alipayConfigsService.getAppIdInfo(appIdStr);
        //通过appId获取对应的账号信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, appIdInfo.getAlipayPublicKey(), AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.info("验证公钥时出现异常");
        } // 调用SDK验证签名
        logger.info("验证签名结果" + signVerified);
        //对应数据库操作
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            logger.info("-----------商户订单号" + out_trade_no);
            logger.info("-----------支付宝交易号" + trade_no);
            logger.info("-----------交易状态" + trade_status);
            //订单支付成功
            if ("TRADE_SUCCESS".equals(trade_status)) {
                try {
                    appNoPayService.clearAlipay();
                }catch (Exception e){
                }

                //根据订单号、支付状态、支付方式获取预订单
//                VipOrder vipOrder = vipOrderService.infoByOrderNo(out_trade_no);
                VipOrder vipOrder = vipOrderService.getByOrderNum(out_trade_no, dingdan_zhiFuLeiXing_zfb, 0);
//                if (ObjectUtil.isNotEmpty(vipOrder)
//                        && !vipOrder.getVipPackageId().equals(1000)
//                ) {
//                    //更改订单状态
//                    vipOrderService.successCall(out_trade_no);
//                } else {
//                    VipOrder vipOrder1 = vipOrderService.infoByOrderNo(out_trade_no);
//                    vipOrder1.setStatus(1);
//                    vipOrderDao.update(vipOrder1);
//                    //更改状态
//                    appUserService.upstateWindowTicket(vipOrder.getUserId());
//                }

                if (ObjectUtil.isNotEmpty(vipOrder)) {
                    Integer vipPackageId = vipOrder.getVipPackageId();
                    //门票
                    if (vipPackageId.equals(1000)) {

                        VipOrder vipOrder1 = vipOrderService.infoByOrderNo(out_trade_no);
                        vipOrder1.setStatus(1);
                        vipOrderDao.update(vipOrder1);
                        //更改状态
                        appUserService.upstateWindowTicket(vipOrder.getUserId());
                        afterUserService.upWhiteStatus(vipOrder.getUserId(), 2);
                    }
                    //会员
                    if (vipPackageId.equals(101) || vipPackageId.equals(102) || vipPackageId.equals(103) || vipPackageId.equals(100)) {

                        //更改订单状态
                        vipOrderService.successCall(out_trade_no);
                        afterUserService.upWhiteStatus(vipOrder.getUserId(), 2);
                    }


                    //php

                    //4 门票
                    if (vipPackageId.equals(4)) {

                        VipOrder vipOrder1 = vipOrderService.infoByOrderNo(out_trade_no);
                        vipOrder1.setStatus(1);
                        vipOrderDao.update(vipOrder1);
                        //生成门票数据
                        phpUserService.callBackWindowTick(vipOrder1.getUserId());

                        //回调php


                        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中

                        Integer types = 1;

                        String param = "key:26e97719fb48687d42681b0ead73c418,uid:" + vipOrder1.getUserId() + ",money:" + vipOrder1.getPrice() + ",type:" + types;

                        String ss = Md5Util1.md5Hex(param);

                        HashMap<String, Object> paramMap = new HashMap<>();

                        paramMap.put("singer", ss);
                        paramMap.put("uid", vipOrder1.getUserId());
                        paramMap.put("money", vipOrder1.getPrice());
                        paramMap.put("type", types);
                        String result = HttpUtil.get("https://poposeapi.ptszyxx.com/apa/Shujuhaonv/play", paramMap);

                        System.out.println(result);


                    }
                    //会员  1三天  2一个月  3六个月  7 12个月
                    if (vipPackageId.equals(1) || vipPackageId.equals(2) || vipPackageId.equals(3) || vipPackageId.equals(7)) {

                        VipOrder vipOrder1 = vipOrderService.infoByOrderNo(out_trade_no);
                        vipOrder1.setStatus(1);
                        vipOrderDao.update(vipOrder1);
                        //生成会员数据
                        phpUserService.callBackVip(vipOrder1.getUserId(), vipPackageId);

                        Integer types = null;

                        if (vipPackageId.equals(1)){
                            types = 2;
                        }
                        if (vipPackageId.equals(2)){
                            types = 3;
                        }
                        if (vipPackageId.equals(3)){
                            types = 4;
                        }
                        if (vipPackageId.equals(7)){
                            types = 5;
                        }
                        String param = "key:26e97719fb48687d42681b0ead73c418,uid:" + vipOrder1.getUserId() + ",money:" + vipOrder1.getPrice() + ",type:" + types;

                        String ss = Md5Util1.md5Hex(param);

                        HashMap<String, Object> paramMap = new HashMap<>();

                        paramMap.put("singer", ss);
                        paramMap.put("uid", vipOrder1.getUserId());
                        paramMap.put("money", vipOrder1.getPrice());
                        paramMap.put("type", types);
                        String result = HttpUtil.get("https://poposeapi.ptszyxx.com/apa/Shujuhaonv/play", paramMap);

                        System.out.println(result);

                    }
                }
                logger.info("支付宝回调成功，充值入账成功");
            }
        }
        return "success";
    }

    /**
     * 永安支付
     */
    @RequestMapping(value = "/fei/notifyUrl1", method = RequestMethod.POST)
    @ResponseBody
    public String feiNotifyUrl1(@RequestBody FeiParam1 param) {
        System.out.println(param);
        if(1 == param.getStatus()){
            String orderNo = param.getMerOrderTid();
            doNotifyUrl(orderNo);
        }
        return "success";
    }

    /**
     * 汇付天下
     */
    @RequestMapping(value = "/fei/notifyUrl2", method = RequestMethod.POST)
    @ResponseBody
    public String feiNotifyUrl2(@RequestBody FeiParam2 param) {
        System.out.println(param);
        if(ObjectUtil.isNotEmpty(param.getData()) && ObjectUtil.equal(1, param.getData().getState())){
            String orderNo = param.getData().getMerchant_order_no();
            doNotifyUrl(orderNo);
        }
        return "success";
    }

    /**
     * 支付宝16：
     */
    @RequestMapping(value = "/fei/notifyUrl3", method = RequestMethod.POST)
    @ResponseBody
    public String feiNotifyUrl3(FeiParam3 param) {
        if(ObjectUtil.equal(2, param.getStatus())){
            String orderNo = param.getMchOrderNo();
            doNotifyUrl(orderNo);
        }
        return "success";
    }

    /**
     * 奈斯支付：
     */
    @RequestMapping(value = "/fei/notifyUrl4", method = RequestMethod.POST)
    @ResponseBody
    public String feiNotifyUrl4(FeiParam4 param) {
        if(ObjectUtil.equal("00", param.getReturncode())){
            String orderNo = param.getOrderid();
            doNotifyUrl(orderNo);
        }
        return "OK";
    }

    private void doNotifyUrl(String orderNo) {
        VipOrder order = vipOrderService.infoByOrderNo(orderNo);
        //处理待支付的订单
        if(ObjectUtil.isNotEmpty(order) && ObjectUtil.equal(order.getStatus(), 0)){
            Integer vipPackageId = order.getVipPackageId();
            //门票
            if(ObjectUtil.equal(1000, vipPackageId)){
                order.setStatus(1);
                vipOrderDao.update(order);
                appUserService.upstateWindowTicket(order.getUserId());
                afterUserService.upWhiteStatus(order.getUserId(), 2);
            }
            //vip
            else if (vipPackageId.equals(101) || vipPackageId.equals(102) || vipPackageId.equals(103) || vipPackageId.equals(100)) {
                vipOrderService.successCall(orderNo);
                afterUserService.upWhiteStatus(order.getUserId(), 2);
            }
        }
    }


}
